<template> 
  <teleport to="body">
    <el-dialog
      :title="isRegistering ? '用户注册' : '用户登录'"
      v-model="visible"
      width="400px"
      center
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-form @submit.prevent="isRegistering ? handleRegister() : handleLogin()" label-position="top">
        <el-form-item label="用户名">
          <el-input v-model="username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>

        <el-form-item v-if="isRegistering" label="确认密码">
          <el-input v-model="confirmPassword" type="password" show-password placeholder="请再次输入密码" />
        </el-form-item>

        <p v-if="error" class="error">{{ error }}</p>
      </el-form>

      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="isRegistering ? handleRegister() : handleLogin()">
          {{ isRegistering ? '注册' : '登录' }}
        </el-button>
        <el-button type="text" @click="toggleForm">
          {{ isRegistering ? '已有账号？去登录' : '没有账号？去注册' }}
        </el-button>
      </template>
    </el-dialog>
  </teleport>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import * as apiUser from '@/api/user'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(props.modelValue)
watch(() => props.modelValue, val => (visible.value = val))
watch(visible, val => emit('update:modelValue', val))

const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const error = ref('')
const isRegistering = ref(false)
const router = useRouter()
const userStore = useUserStore()

function toggleForm() {
  isRegistering.value = !isRegistering.value
  error.value = ''
  username.value = ''
  password.value = ''
  confirmPassword.value = ''
}

async function handleLogin() {
  if (!username.value || !password.value) {
    error.value = '用户名和密码不能为空'
    return
  }

  try {
    const res = await apiUser.loginApi({
      username: username.value,
      password: password.value,
    })

    const { code, message, data } = res
     console.log('✅ 登录响应:', code)
    if (code === 0) {
      const { token, user } = data

      userStore.setToken(token)
      userStore.setUserInfo({
        id: user.id,
        username: user.user_name,
        usertype: user.type,
      })

      error.value = ''
      emit('success')
      visible.value = false
      router.push('/')
    } else {
      error.value = message || '登录失败'
    }
  } catch (e :any) {
     if (e.response?.status === 401) {
      error.value = '账户或密码错误'
    } else {
      error.value = '登录请求失败'
    }
  }
}

async function handleRegister() {
  if (!username.value || !password.value) {
    error.value = '用户名和密码不能为空'
    return
  }
  if (password.value !== confirmPassword.value) {
    error.value = '两次密码输入不一致'
    return
  }

  try {
    const res = await apiUser.registerApi({
      username: username.value,
      password: password.value,
    })

    console.log('✅ 注册响应:', res)

    const { code, message } = res
    if (code === 0) {
      ElMessage.success('注册成功，等待管理审核！')
      error.value = ''
      visible.value = false
      isRegistering.value = false
      username.value = ''
      password.value = ''
      confirmPassword.value = ''
    } else {
      error.value = message || '注册失败'
    }
  } catch (e) {
    error.value = '注册请求失败'
  }
}
</script>

<style scoped>
.error {
  color: red;
  text-align: center;
  margin-top: 12px;
  font-size: 14px;
}
</style>
